package com.samphanie.security.validation.service;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.samphanie.common.utils.MyRequestWrapper;
import com.samphanie.security.domain.Captcha;
import com.samphanie.security.validation.enums.ValidateCodeType;
import com.samphanie.security.validation.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Slf4j
public abstract class AbstractValidateCodeProcessor<C extends Captcha> implements ICaptchaService {

    /**
     * 收集系统中所有的 {@link ValidateCodeGenerator} 接口的实现。
     */
    @Resource
    private Map<String, ValidateCodeGenerator> validateCodeGenerators;
    @Resource
    private ValidateCodeMapper validateCodeMapper;

    /**
     * 渲染验证码
     */
    @Override
    public Captcha render(ServletWebRequest request) {

        C validateCode = generate(request);
        Captcha captcha = save(request, validateCode);
        send(request, validateCode);

        return captcha;
    }

    /**
     * 生成校验码
     */
    @SuppressWarnings("unchecked")
    private C generate(ServletWebRequest request) {
        String type = getValidateCodeType(request).toString().toLowerCase();
        String generatorName = type + ValidateCodeGenerator.class.getSimpleName();
        ValidateCodeGenerator validateCodeGenerator = validateCodeGenerators.get(generatorName);
        if (validateCodeGenerator == null) {
            throw new ValidateCodeException("验证码生成器" + generatorName + "不存在");
        }
        return (C) validateCodeGenerator.generate(request);
    }

    /**
     * 保存校验码
     */
    private Captcha save(ServletWebRequest request, C validateCode) {

        // Captcha code = new Captcha(IdUtil.simpleUUID(),validateCode.getCode(), validateCode.getExpireTime());
        var code = Captcha.builder().uuid(IdUtil.simpleUUID()).code(validateCode.getCode()).expireTime(validateCode.getExpireTime()).build();
        log.info("保存效验码==========》{}", validateCode.getCode());
        validateCodeMapper.save(request, code, getValidateCodeType(request));

        return code;
    }

    /**
     * 发送校验码，由子类实现
     */
    protected abstract void send(ServletWebRequest request, C validateCode);

    /**
     * 根据请求的url获取校验码的类型
     */
    private ValidateCodeType getValidateCodeType(ServletWebRequest request) {
        String type = StrUtil.subBefore(getClass().getSimpleName(), "CodeProcessor", false);
        return ValidateCodeType.valueOf(type.toUpperCase());
    }

    @Override
    public void validate(ServletWebRequest request, MyRequestWrapper requestWrapper) {
        ValidateCodeType codeType = getValidateCodeType(request);
        C codeInSession = (C) validateCodeMapper.get(request, codeType);

        String codeInRequest;
        try {
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "code");
            if (StrUtil.isBlank(codeInRequest)) {
                JSONObject obj = JSONUtil.parseObj(requestWrapper.getBody());
                codeInRequest = (String) obj.get("code");
            }
        } catch (Exception e) {
            throw new ValidateCodeException("获取验证码失败");
        }

        validateCode(request, codeType, codeInSession, codeInRequest);
    }

    @Override
    public void validate(ServletWebRequest request, String code) {
        ValidateCodeType codeType = getValidateCodeType(request);
        C codeInSession = (C) validateCodeMapper.get(request, codeType);
        validateCode(request, codeType, codeInSession, code);
    }

    private void validateCode(ServletWebRequest request, ValidateCodeType codeType, C codeInSession, String codeInRequest) {
        if (StrUtil.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }
        if (codeInSession == null) {
            throw new ValidateCodeException("验证码不存在");
        }
        if (codeInSession.isExpired()) {
            validateCodeMapper.remove(request, codeType);
            throw new ValidateCodeException("验证码已过期");
        }
        if (!StrUtil.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }
        // 移除验证码
        if (StrUtil.equals(codeInSession.getCode(), codeInRequest)) {
            validateCodeMapper.remove(request, codeType);
        }
    }
}
